import 'package:flutter/material.dart';
import 'package:flutter_billi/db/hi_cache.dart';
import 'package:flutter_billi/http/dao/login_dao.dart';
import 'package:flutter_billi/model/video_model.dart';
import 'package:flutter_billi/navgator/bottom_navigator.dart';
import 'package:flutter_billi/page/detail_page.dart';
import 'package:flutter_billi/page/login_page.dart';
import 'package:flutter_billi/page/registrion_page.dart';
import 'package:flutter_billi/util/color.dart';
import 'package:flutter_billi/util/toast.dart';
import 'navgator/hi_navigator.dart';

void main() {
  runApp(BiliApp());
}

class BiliApp extends StatefulWidget {
  @override
  _BiliAppState createState() => _BiliAppState();
}

class _BiliAppState extends State<BiliApp> with AutomaticKeepAliveClientMixin {
  BiliRouteDelegate _routeDelegate = new BiliRouteDelegate();

  var Listener;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // HiNavigator.getInstance().removeListener(this.Listener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<HiCache>(
        // 初始化
        future: HiCache.preInit(),
        builder: (BuildContext context, AsyncSnapshot<HiCache> snapshot) {
          var widget = snapshot.connectionState == ConnectionState.done
              ? Router(
                  routerDelegate: _routeDelegate,
                )
              : Scaffold(
                  body: Center(
                  child: CircularProgressIndicator(),
                ));
          return MaterialApp(
            home: widget,
            theme: ThemeData(primarySwatch: white),
          );
        });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

// 创建路由代理
class BiliRouteDelegate extends RouterDelegate<BiliRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<BiliRoutePath> {
  final GlobalKey<NavigatorState> navigatorKey;

  BiliRouteDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
    // 实现跳转逻辑
    HiNavigator.getInstance().registerRouteJump(RouteJumpListener(onJumpTo: (RouteStatus routeStatus, {Map args}) {
      print(routeStatus);
      print(args);
      _routeStatus = routeStatus;
      if (_routeStatus == RouteStatus.detail) {
        videoModal = args['videoMo'];
      }
      notifyListeners();
    }));
  }

  List<MaterialPage> pages = [];

  VideoModel videoModal;

  RouteStatus _routeStatus = RouteStatus.home;

  @override
  Widget build(BuildContext context) {
    // pages = [];
    // 构建路由堆栈
    // 管理路由堆栈
    var index = getPageIndex(pages, routeStatus);
    List<MaterialPage> tempPages = pages;
    if (index != -1) {
      // index 之前的页面 全部出栈，显示 indx 所指的页面
      tempPages = tempPages.sublist(0, index);
    }
    var page;
    if (routeStatus == RouteStatus.home) {
      pages.clear();
      page = pageWarp(BottomNavigator());
    } else if (routeStatus == RouteStatus.detail) {
      page = pageWarp(VideoDetailPage(videoModal));
    } else if (routeStatus == RouteStatus.registration) {
      page = pageWarp(RegistrationPage());
    } else if (routeStatus == RouteStatus.login) {
      page = pageWarp(LoginPage());
    }
    tempPages = [...tempPages, page];
    HiNavigator.getInstance().notify(tempPages, pages);
    pages = tempPages;

    return WillPopScope(
        onWillPop: () async => !await navigatorKey.currentState.maybePop(),
        child: Navigator(
          key: navigatorKey,
          pages: pages,
          onPopPage: (route, result) {
            if ((route.settings as MaterialPage).child is LoginPage) {
              if (!hasLogin) {
                showToast('请先登陆');
                return false;
              }
            }
            // 关闭页面

            if (!route.didPop(result)) return false;
            var tempPages = [...pages];
            pages.removeLast();
            // 通知路由变化
            HiNavigator.getInstance().notify(pages, tempPages);

            return true;
          },
        ));
  }

  RouteStatus get routeStatus {
    // 用户没有登陆 ，并且不是处在 非注册页面
    print("登陆成功${hasLogin}");
    if (_routeStatus != RouteStatus.registration && !hasLogin) {
      return _routeStatus = RouteStatus.login;
    } else if (videoModal != null) {
      return _routeStatus = RouteStatus.detail;
    } else {
      return _routeStatus;
    }
  }

  bool get hasLogin => LoginDao.getBoardingPass() != null;

  @override
  Future<void> setNewRoutePath(BiliRoutePath configuration) {
    // TODO: implement setNewRoutePath
    throw UnimplementedError();
  }
}

// 定义路由数据
class BiliRoutePath {
  final String location;
  BiliRoutePath.home() : location = "/";

  BiliRoutePath.detail() : location = "/detail";
}
